package system

import (
	"context"
	v1 "gf-vben-admin/api/system/v1"
	model "gf-vben-admin/internal/model/system"
	sysEntity "gf-vben-admin/internal/model/system/entity"
	"gf-vben-admin/internal/service/auth"
	service "gf-vben-admin/internal/service/system"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/util/gconv"
)

var (
	User = cUser{}
)

type cUser struct{}

func (c *cUser) PageList(ctx context.Context, req *v1.UserPageListReq) (res *v1.UserPageListRes, err error) {
	in := new(model.User)
	err = gconv.Struct(req, in)
	if err != nil {
		return nil, err
	}
	total, list, err := service.User().PageList(ctx, *in)
	if err != nil {
		return nil, err
	}
	res = &v1.UserPageListRes{
		Total: total,
		Rows:  list,
	}
	return
}

func (c *cUser) List(ctx context.Context, req *v1.UserListReq) (res *v1.UserListRes, err error) {
	in := new(model.User)
	err = gconv.Struct(req, in)
	if err != nil {
		return nil, err
	}
	list, err := service.User().List(ctx, *in)
	if err != nil {
		return nil, err
	}
	res = &v1.UserListRes{
		Rows: list,
	}
	return
}

func (c *cUser) Add(ctx context.Context, req *v1.UserAddReq) (res *v1.UserAddRes, err error) {
	in := new(model.User)
	err = gconv.Struct(req, in)
	if err != nil {
		return nil, err
	}
	err = service.User().Add(ctx, *in)
	return
}

func (c *cUser) Edit(ctx context.Context, req *v1.UserEditReq) (res *v1.UserEditRes, err error) {
	in := new(model.User)
	err = gconv.Struct(req, in)
	if err != nil {
		return nil, err
	}
	err = service.User().Edit(ctx, *in)
	return
}

func (c *cUser) EditState(ctx context.Context, req *v1.UserEditStateReq) (res *v1.UserEditRes, err error) {
	err = service.User().EditState(ctx, req.Ids, req.State)
	return
}

func (c *cUser) Delete(ctx context.Context, req *v1.UserDelReq) (res *v1.UserDelRes, err error) {
	err = service.User().Delete(ctx, req.Ids)
	return
}

func (c *cUser) Info(ctx context.Context, req *v1.UserGetInfoReq) (res *v1.UserGetInfoRes, err error) {
	userInfo := auth.Auth().GetPayload(ctx)
	user := new(sysEntity.User)
	err = gjson.New(userInfo).Scan(user)
	if err != nil {
		return nil, err
	}
	return &v1.UserGetInfoRes{
		User: *user,
	}, nil
}
